package com.fudan.es.aggs;

import java.util.List;

import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fudan.biz.data.service.FieldMetaService;
import com.fudan.es.aggs.entity.MetricDef;
import com.fudan.es.aggs.handler.base.AggsHandler;
import com.fudan.es.entity.FieldMeta;
import com.fudan.es.entity.MetricPack;
import com.fudan.es.entity.MetricPack.MetricType;
@Component
public class MetricParser {

	protected static final String ROOT_PATH = ConstString.ROOT_PATH;

	@Autowired
	private FieldMetaService fieldMetaService;

	public AggregationBuilder build(MetricPack metric) {
		MetricType metricType = metric.getType();
		//MetricHandler handler = MetricHandler.buildHandler(metricType);
		//handler.handle(null,metric);
		AggsHandler metricHandler = AggsHandler.buildHandler(metricType);
		metricHandler.handle(null, metric);
		System.out.println(metric.getRoot());
		return metric.getRoot();
	}

	public MetricPack build(MetricDef metric) {
		String type = metric.getType();
		String fieldId = metric.getField();
		FieldMeta field = fieldMetaService.get(fieldId);
		MetricType metricType = MetricType.valueOf(type.toUpperCase());
		MetricPack metricPack = MetricPack.build(field,metricType,metric);
		String grainDef = metric.getGrain();
		if(grainDef != null) {
			if(grainDef.equals(ROOT_PATH)) {
				FieldMeta grainField = new FieldMeta();
				grainField.setName(ROOT_PATH);
				metricPack.setGrain(grainField);
			}else {
				FieldMeta grainField = fieldMetaService.get(grainDef);
				metricPack.setGrain(grainField);
			}
		}
		setConfig(metric,metricPack);
		metricPack.generateAggregation();
		List<MetricDef> subMetric = metric.getMetric();
		if(subMetric != null) {
			for (MetricDef subDef : subMetric) {
				MetricPack sub = build(subDef);
				metricPack.add(sub);
			}
		}
		return metricPack;
	}

	private void setConfig(MetricDef metricDef,MetricPack metricPack) {
		Integer size = metricDef.getSize();
		if(size != null && size > 0) {
			metricPack.setSize(size);
		}
		String missing = metricDef.getMissing();
		if(missing!=null && !"".equals(missing)) {
			metricPack.setMissing(missing);
		}
		String other = metricDef.getOther();
		if(other!=null&&!"".equals(other)) {
			metricPack.setOther(other);
		}
	}
}
